from zope.interface import implements, Interface

from Products.Five import BrowserView
from Products.CMFCore.utils import getToolByName
from zope.component import getUtility
from zope.component import getMultiAdapter
from Acquisition import aq_inner
from plone.memoize.instance import memoize


from zope.i18n.interfaces import ITranslationDomain
from zope.component import queryUtility

from Products.CMFCore.interfaces import ISiteRoot
from Products.AdvancedQuery import Eq, Between, Le

from my315ok.xtjxwcontents.interfaces.jiaxiao import Ijiaxiao
from my315ok.xtjxwcontents import xtjxwcontentsMessageFactory as _


class Ijiaxiao_folderView(Interface):
    """
    jiaxiao_folder view interface
    """

    def test():
        """ test method"""


class jiaxiao_folderView(BrowserView):
    """
    jiaxiao_folder browser view
    """
    implements(Ijiaxiao_folderView)


    def __init__(self, context, request):
        self.context = context
        self.request = request

    @property
    def portal_catalog(self):
        return getToolByName(self.context, 'portal_catalog')

    @property
    def portal(self):
        return getToolByName(self.context, 'portal_url').getPortalObject()

    def query(self):
        """
        compose query string
        
        """
        portal = getUtility(ISiteRoot)
        catalog = getToolByName(portal, 'portal_catalog')
        aq = catalog.makeAdvancedQuery({'review_state': 'published','object_provides':Ijiaxiao.__identifier__})
        if "SearchableText" in self.request.form.keys():
            term = self.request.form["SearchableText"]
            term = term.strip()
            if len(term)!=0:
                query = Eq("SearchableText",term) | Eq('Description',term)
                return query
                
        raw = self.request["QUERY_STRING"]
        if len(raw) != 0:
            phase = raw.split("&")

            for st2 in phase:                
                st = st2.split("=")
                pa = st[0]
                val = st[-1]
            
                if "-" in val:

                    low = val.split("-")[0]
                    hight = val.split("-")[-1]
                    query = Between(pa,float(low),float(hight))
                
                else:

                    query = Eq(pa, val)

                aq &= query 
        return aq
    @memoize   
    def results(self):
#        import pdb
#        pdb.set_trace()
        portal = getUtility(ISiteRoot)
        catalog = getToolByName(portal, 'portal_catalog')
        query = self.query()
#        for i in len(kw):
#            p = kw['keys'][i] 
#            val = kw['values'][i]
#            tmp = Eq(p,val)
#            qstr &= tmp
#        query = query & qstr    
        if query == "" or query ==None:
            return []
        result = catalog.evalAdvancedQuery(query)
        return result


    def getURL(self,brain):
        path = brain.getPath()
#        return brain.getURL()
        context = aq_inner(self.context)
        portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state')
        root = portal_state.navigation_root_url()
        d = path.split("/")
        return  root + "/" + "/".join(d[2:])
      

    @memoize
    def getArea(self):
#        import pdb
#        pdb.set_trace()
        portal = getUtility(ISiteRoot)
        catalog = getToolByName(portal, 'portal_catalog')  
        brains = catalog(object_provides=Ijiaxiao.__identifier__)
        lt = []
        for ss in brains:
            t = ss.district.strip()
            try:
                lent = len(t)
            except:
                continue

            if lent !=0 and t not in lt:
                lt.append(t)
#                continue
        return lt
    def translates(self,item):
#        import pdb
#        pdb.set_trace()      
        
        util = queryUtility(ITranslationDomain, 'my315ok.xtjxwcontents')    
        tted = util.translate(item,target_language="zh",
                                       default="xiangtanshihexi")           
        return tted
    
    def getImage(self,brain,scale="tile"):
        
        if scale=="orig":
            ext = "/image"
        else:
            ext = "/image_%s" % scale
#        base = brain.getURL()        
        base = self.getURL(brain)
        title = brain.Title
        url = base + '/main.png' + ext
        portal = self.portal
#        import pdb
#        pdb.set_trace()
        p_url = portal.absolute_url()
        existimg = portal.unrestrictedTraverse(url, default=None)
        if existimg == None:
            url = p_url + "/++resource++schoolwatermark.png" 
            url = base + '/main.png' + ext                           
        htmltag = "<img src='%s' alt='%s' />" %(url,title)
        return htmltag
                
        
    def test(self,t,a,b):
        """ test method"""   
        if t:
            return a
        else:
            return b